package com.example.zhinongbao.base;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.example.zhinongbao.presenter.MainPresenter;

import java.lang.ref.WeakReference;

/**
 * A handler that uses a weak reference to its associated object, preventing the
 * object from being accidentally retained by the handler.
 *
 * @param <T> The type of object that this handler is associated with.
 */
public class WeakRefHandler<T> extends Handler {
    private WeakReference<T> mWeakReference;
    private Callback<T> mCallback;

    /**
     * Constructs a new instance of WeakRefHandler.
     *
     * @param looper    The looper associated with the thread this handler should
     *                  operate on.
     * @param t         The object to associate with this handler, held with a
     *                  weak reference.
     * @param callback  The callback to handle messages.
     */
    public WeakRefHandler(Looper looper, T t, Callback<T> callback) {
        super(looper);
        mCallback = callback;
        mWeakReference = new WeakReference<>(t);
    }



    /**
     * Handles messages by delegating to the associated callback, if the associated
     * object is still alive.
     */
    @Override
    public void handleMessage(Message msg) {
        T t = mWeakReference.get();
        if (t != null && mCallback != null) {
            try {
                mCallback.handleMessage(t, msg);
            } catch (Exception e) {
                // Handle or log the exception as appropriate
            }
        }
    }

    /**
     * Retrieves the weak reference to the associated object.
     *
     * @return The associated object, or null if it has been garbage collected.
     */
    public T getReference() {
        return mWeakReference.get();
    }

    /**
     * Checks if the associated object is still alive.
     *
     * @return True if the associated object has not been garbage collected.
     */
    public boolean isAlive() {
        return mWeakReference.get() != null;
    }

    /**
     * Interface definition for callback to be invoked when a message is handled.
     *
     * @param <T> The type of object associated with the handler.
     */
    public interface Callback<T> {
        void handleMessage(T associatedObject, Message msg);
    }
}